﻿using System;
using Transformable_Engine_v2.Engine.Animation.Trajectory;
using Transformable_Engine_v2.Engine.Global;
using Transformable_Engine_v2.Engine.Graphics;

namespace Transformable_Engine_v2.Engine.Animation.ColorAnimation
{
    public class ColorAnimation : BaseAnimation
    {
        public IColorAnimatable AffectedObject { private get; set; }
        private readonly ITrajectory _trajectory;

        private Color _beginColor;
        private Color _currentColor;
        private readonly Color _endColor;

        public override void Update(TimeSpan gameTime)
        {
            
        }

        public override void FixedStepUpdate(TimeSpan gameTime)
        {
            if(IsAlive() && IsStarted) {
                double elapsed = _trajectory.GetPercentageProgression(DurationTimer.PercentageElapsed);
                Color nextColor = (_endColor - _beginColor) * elapsed + _beginColor;

                if(AffectedObject != null)
                    AffectedObject.AddToColor(nextColor - _currentColor);
                _currentColor = nextColor;
            }

            base.FixedStepUpdate(gameTime);
        }

        protected override void DelayEnd()
        {
            _beginColor = AffectedObject.GetColor();

            _currentColor = _beginColor;

            Log.LogDebug(this.ToString());

            base.DelayEnd();
        }

        public override string ToString()
        {
            return string.Format("Color from {0} to {1}", _beginColor, _endColor);
        }

        protected override void DurationEnd()
        {
            if (!IsLooping)
            {
                AffectedObject.AddToColor(_endColor - _currentColor);
                _currentColor = _endColor;
            }
            base.DurationEnd();
        }

        public ColorAnimation(ITrajectory trajectory, Color targetColor,
                                    double duration, bool isLooping = false, double delay = 0, bool autoStart = true)
            : base(duration, isLooping, delay, autoStart)
        {
            _trajectory = trajectory;

            _endColor = targetColor;
        }

    }
}